package cn.edu.cug.cs.gtl.docsrv.doc.service.impl;

import cn.edu.cug.cs.gtl.docsrv.doc.dao.DocDao;
import cn.edu.cug.cs.gtl.docsrv.doc.service.DocService;
import cn.edu.cug.cs.gtl.mybatis.mapper.doc.DocAll;
import cn.edu.cug.cs.gtl.mybatis.mapper.doc.DocItem;
import cn.edu.cug.cs.gtl.protos.TimeValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class DocServiceImpl implements DocService {

    @Autowired
    DocDao docDao;

    public DocServiceImpl() {
        super();
    }


    @Override
    public List<DocAll> getDocData() throws Exception {
        return docDao.getDocData();
    }



    @Override
    public boolean addDocData(DocAll docAll) throws Exception {
        return docDao.addDocData(docAll);
    }

    @Override
    public boolean deleteDocData(BigDecimal docInternalId) throws Exception {
        return docDao.deleteDocData(docInternalId);
    }

    @Override
    public boolean updateDocData(DocAll docAll) throws Exception {
        return docDao.updateDocData(docAll);
    }

    @Override
    public List<DocAll> singleQuery(String column, String value) throws Exception {
        return docDao.singleQuery(column, value);
    }

    @Override
    public List<DocAll> dateQuery(TimeValue begin, TimeValue end) throws Exception {
        return docDao.dateQuery(begin,end);
    }

    @Override
    public void downloadDocFile(BigDecimal docInternalId, HttpServletResponse response) throws Exception {
        ServletOutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            outputStream = response.getOutputStream();
            inputStream = docDao.downloadDocFile(docInternalId);
            byte[] buffer = new byte[2048];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } finally {
            if (inputStream != null){
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

}
